接下來我們寫好前端後把部署上的後端程式都串接起來!
chatApi.js
const API_URL = '/api/vertexai/chat';
export const sendChatMessage = async (message) => {
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message }),
});
if (!response.ok) {
throw new Error('API request failed');
}
const data = await response.json();
return data.response;
} catch (error) {
console.error('Error:', error);
throw error;
}
};
修改ChatInterface .jsx
import { sendChatMessage } from '../api/chatApi';
const ChatInterface = () => {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const messagesEndRef = useRef(null);
const sendMessage = async () => {
if (input.trim()) {
setMessages([...messages, { text: input, sender: 'user' }]);
setInput('');
setIsLoading(true);
try {
const response = await sendChatMessage(input.trim());
setMessages(msgs => [...msgs, { text: response, sender: 'ai' }]);
} catch (error) {
console.error('Error:', error);
setMessages(msgs => [...msgs, { text: '抱歉,发生错误。请稍后再试。', sender: 'ai' }]);
} finally {
setIsLoading(false);
}
}
};
嘗試的過程中,會遇到跨域問題,類似以下錯誤!
Access to fetch at 'https://xxxx/vertexai/chat' from origin 'http://localhost:5173'
has been blocked by CORS policy: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. If an opaque response serves your needs,
set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
嘗試修改了一下vite.config.js 前端臨時解決方案,無法立即修改後端,可以在前端使用代理服務器來繞過CORS限制。這只是一個開發階段的臨時解決方案,不應在生產環境中使用。
PS:target為Cloud Run url
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
historyApiFallback: true,
proxy: {
'/api': {
target: 'https://xxxx',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},
})
聊天看起來是很順利!
點選右上角我們還有把檔案轉成向量的方式的功能測試!(前提是要把API串起來這裡就不再展示一遍)
看起來也是可以正常進入DB!
最後再問他我們剛剛丟入的資料內容!
看來內容跟我做向量資料的內容可說是87%像XD
明天我們就嘗試把前端也部署到雲端上使用!